package cn.liwq.demo.serializer;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * 浮点数序列化器
 *
 * @author lweiqiang
 * @date 2023/1/31
 */
public class ScaleSerializer extends StdSerializer<Object> {

  private static final long serialVersionUID = 1L;

  private final int scale;

  private final RoundingMode roundingMode;

  public ScaleSerializer(int scale, RoundingMode roundingMode) {
    super(Object.class);
    this.scale = scale;
    this.roundingMode = roundingMode;
  }

  @Override
  public void serialize(Object decimal, JsonGenerator gen, SerializerProvider provider)
      throws IOException {
    if (Objects.isNull(decimal) || StrUtil.isBlank(decimal.toString())) {
      gen.writeNull();
      return;
    }
    BigDecimal data;
    if (decimal instanceof BigDecimal) {
      data = (BigDecimal) decimal;
    } else {
      data = new BigDecimal(decimal.toString());
    }
    gen.writeRawValue(data.setScale(scale, roundingMode).toPlainString());
  }
}
